package com.csun.cmny.provider.controller.admin;

import com.csun.cmny.core.annotation.ValidateAnnotation;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.device.csun.gateway.entity.CsunGatewayData;
import com.csun.cmny.provider.model.constant.DeviceConstant;
import com.csun.cmny.provider.model.constant.OnlineConstant;
import com.csun.cmny.provider.model.domain.*;
import com.csun.cmny.provider.model.dto.device.DmcEditDeviceDto;
import com.csun.cmny.provider.model.dto.humidistat.BindCsunHumidistatLocationDto;
import com.csun.cmny.provider.model.dto.humidistat.CsunHumidistatQueryDto;
import com.csun.cmny.provider.model.enums.device.DeviceStatusEnum;
import com.csun.cmny.provider.model.enums.device.DmcDeviceTypeEnum;
import com.csun.cmny.provider.model.vo.RoomBuildingVo;
import com.csun.cmny.provider.model.vo.humidistat.CsunHumidistatVo;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.validator.DmcDeviceEditValidator;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.RedisKeyUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-12-27 15:05
 * @Description:
 */
@RestController
@RequestMapping(value = "/humidistat", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DmcCsunHumidistatController extends BaseController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private CmnyMessageSource cmnyMessageSource;
    @Resource
    private DmcCsunHumidistatLocationService dmcCsunHumidistatLocationService;
    @Resource
    private DmcDeviceService dmcDeviceService;
    @Resource
    private DmcCsunGatewayBindService dmcCsunGatewayBindService;
    @Resource
    private DmcDeviceOnlineRecordService dmcDeviceOnlineRecordService;


    /**
     * 查询温湿度传感器
     *
     * @param csunHumidistatQueryDto the csun humidistat query dto
     * @return the wrapper.
     */
    @RequestMapping(value = "/queryListWithPage", method = RequestMethod.POST)
    public Wrapper queryListWithPage(@RequestBody CsunHumidistatQueryDto csunHumidistatQueryDto) {

        csunHumidistatQueryDto.setGroupId(getLoginAuthDto().getGroupId());
        csunHumidistatQueryDto.setDeviceType(DmcDeviceTypeEnum.HUMIDISTAT.getIndex());

        List<CsunHumidistatVo> csunHumidistatVoList = dmcCsunHumidistatLocationService
                .queryListWithPage(csunHumidistatQueryDto);
        for (CsunHumidistatVo chv : csunHumidistatVoList) {

            if (PublicUtil.isNotEmpty(chv.getBindType())) {

                /*
                 * @date 2020-3-12
                 * @author wfb
                 * @desc 新增是否在线状态*/
                /*Boolean aBoolean = redisTemplate.hasKey(RedisKeyUtil.getCsunHumidistatOnline(chv.getDeviceNo()));
                if(aBoolean){
                    chv.setStatus("online");
                }else {
                    chv.setStatus("offline");
                }*/
                String redisKey = RedisKeyUtil.getCsunHumidistatOnline(chv.getDeviceNo());
                String deviceNoQuery = (String) redisTemplate.opsForValue().get(redisKey);
                if (PublicUtil.isEmpty(deviceNoQuery)) {    // 温湿度计已经离线
                    chv.setStatus(DeviceStatusEnum.OFFLINE.getKey());


                } else {
                    chv.setStatus(DeviceStatusEnum.ONLINE.getKey());
                }


                chv.setBind(true);
                switch (chv.getBindType()) {
                    case DeviceConstant.DEVICE_BIND_TYPE_ROOM:
                        RoomBuildingVo vo = (RoomBuildingVo) redisTemplate
                                .opsForValue().get(RedisKeyUtil.getOmcRoomId(chv.getRoomId()));
                        if (PublicUtil.isNotEmpty(vo)) {
                            chv.setBuildingName(vo.getBuildingName());
                            chv.setFloorNo(vo.getFloorNo());
                            chv.setRoomNo(vo.getRoomNo());
                            chv.setOldmanId(vo.getOldmanId());
                            chv.setOldmanName(vo.getOldmanName());
                            chv.setLocation(vo.getRoomNo());
                        }
                        break;
                    case DeviceConstant.DEVICE_BIND_TYPE_LIFE:
                        // 根据life房间Id获取楼栋楼层房间信息
                        RoomBuildingVo roomBuildingVo = (RoomBuildingVo) redisTemplate
                                .opsForValue().get(RedisKeyUtil.getOmcRoomId(chv.getRoomId()));
                        if (PublicUtil.isNotEmpty(roomBuildingVo)) {
                            chv.setBuildingName(roomBuildingVo.getBuildingName());
                            chv.setFloorNo(roomBuildingVo.getFloorNo());
                            chv.setRoomNo(roomBuildingVo.getRoomNo());
                            chv.setOldmanId(roomBuildingVo.getOldmanId());
                            chv.setOldmanName(roomBuildingVo.getOldmanName());
                        }
                        break;
                }
            }
        }

        // return WrapMapper.ok(new PageInfo<>(csunHumidistatVoList));
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), new PageInfo<>(csunHumidistatVoList));
    }

    /**
     * 查询温湿度传感器
     *
     * @param deviceId the csun humidistat query dto
     * @return the wrapper.
     */
    @RequestMapping(value = "/get/{deviceId}", method = RequestMethod.POST)
    public Wrapper get(@PathVariable Long deviceId) {

        CsunHumidistatVo humidistatVo = dmcCsunHumidistatLocationService
                .get(deviceId);



        if (PublicUtil.isNotEmpty(humidistatVo.getBindType())) {

            String redisKey = RedisKeyUtil.getCsunHumidistatOnline(humidistatVo.getDeviceNo());
            String deviceNoQuery = (String) redisTemplate.opsForValue().get(redisKey);
            


            if (PublicUtil.isEmpty(deviceNoQuery)) {    // 温湿度计已经离线
                humidistatVo.setStatus(DeviceStatusEnum.OFFLINE.getKey());
                //如果设备离线状态,不显示温湿度数据
                humidistatVo.setTemperature(null);
                humidistatVo.setHumidity(null);

            } else {
                humidistatVo.setStatus(DeviceStatusEnum.ONLINE.getKey());
            }

            humidistatVo.setBind(true);

            switch (humidistatVo.getBindType()) {

                case DeviceConstant.DEVICE_BIND_TYPE_ROOM:
                    RoomBuildingVo vo = (RoomBuildingVo) redisTemplate
                            .opsForValue().get(RedisKeyUtil.getOmcRoomId(humidistatVo.getRoomId()));
                    if (PublicUtil.isNotEmpty(vo)) {
                        humidistatVo.setBuildingName(vo.getBuildingName());
                        humidistatVo.setFloorNo(vo.getFloorNo());
                        humidistatVo.setRoomNo(vo.getRoomNo());
                        humidistatVo.setOldmanId(vo.getOldmanId());
                        humidistatVo.setOldmanName(vo.getOldmanName());
                        humidistatVo.setLocation(vo.getRoomNo());
                    }
                    break;
                case DeviceConstant.DEVICE_BIND_TYPE_LIFE:
                    // 根据life房间Id获取楼栋楼层房间信息
                    RoomBuildingVo roomBuildingVo = (RoomBuildingVo) redisTemplate
                            .opsForValue().get(RedisKeyUtil.getOmcRoomId(humidistatVo.getRoomId()));
                    if (PublicUtil.isNotEmpty(roomBuildingVo)) {
                        humidistatVo.setBuildingName(roomBuildingVo.getBuildingName());
                        humidistatVo.setFloorNo(roomBuildingVo.getFloorNo());
                        humidistatVo.setRoomNo(roomBuildingVo.getRoomNo());
                        humidistatVo.setOldmanId(roomBuildingVo.getOldmanId());
                        humidistatVo.setOldmanName(roomBuildingVo.getOldmanName());
                    }
                    break;
            }
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), humidistatVo);
    }

    /**
     * 添加温湿度传感器
     *
     * @param dmcEditDeviceDto the dmc edit device dto
     * @param br               the binding result
     * @return the wrapper.
     */
    @ValidateAnnotation
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Wrapper add(@Validated @RequestBody DmcEditDeviceDto dmcEditDeviceDto,
                       BindingResult br) {

        DmcDevice dmcDevice = new DmcDevice();

        BeanUtils.copyProperties(dmcEditDeviceDto, dmcDevice);
        dmcDevice.setDeviceType(DmcDeviceTypeEnum.HUMIDISTAT.getIndex());

        Integer result = dmcDeviceService.addDevice(dmcDevice, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        // return WrapMapper.ok(result);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), result);
    }

    /**
     * 修改温湿度传感器
     *
     * @param dmcEditDeviceDto the dmc edit device dto
     * @param br               the binding result
     * @return the wrapper.
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Wrapper edit(@Validated(value = {DmcDeviceEditValidator.class})
                        @RequestBody DmcEditDeviceDto dmcEditDeviceDto,
                        BindingResult br) {

        DmcDevice dmcDevice = new DmcDevice();
        BeanUtils.copyProperties(dmcEditDeviceDto, dmcDevice);
        dmcDevice.setDeviceType(DmcDeviceTypeEnum.HUMIDISTAT.getIndex());

        Integer result = dmcDeviceService.editDevice(dmcDevice, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), result);
    }

    /**
     * 根据Id删除温湿度传感器
     *
     * @param id the id
     * @return the wrapper.
     */
    @RequestMapping(value = "/deleteById/{id}", method = RequestMethod.POST)
    public Wrapper deleteDmcCsunCameraById(@PathVariable Long id) {

        Integer result = dmcCsunHumidistatLocationService.deleteById(id);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        DmcDeviceOnlineRecord dmcDeviceOnlineRecord = new DmcDeviceOnlineRecord();
        dmcDeviceOnlineRecord.setDeviceId(id);
        int delete = dmcDeviceOnlineRecordService.delete(dmcDeviceOnlineRecord);
        // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), result);
    }

    /**
     * 绑定温湿度传感器
     *
     * @param bindCsunHumidistatLocationDto the bind csun humidistat location dto
     * @param br                            the binding result
     * @return the wrapper
     */
    @RequestMapping(value = "/bind", method = RequestMethod.POST)
    public Wrapper bind(@Validated @RequestBody BindCsunHumidistatLocationDto
                                bindCsunHumidistatLocationDto, BindingResult br) {
        Integer result = dmcCsunHumidistatLocationService
                .bind(bindCsunHumidistatLocationDto, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), result);
    }

    /**
     * 解绑温湿度传感器
     *
     * @param deviceId the device id
     * @return the wrapper.
     */
    @RequestMapping(value = "/untied/{deviceId}", method = RequestMethod.POST)
    public Wrapper untied(@PathVariable Long deviceId) {

        Integer result = dmcCsunHumidistatLocationService.untied(deviceId);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        DmcDeviceOnlineRecord dmcDeviceOnlineRecord = new DmcDeviceOnlineRecord();
        dmcDeviceOnlineRecord.setDeviceId(deviceId);
        int delete = dmcDeviceOnlineRecordService.delete(dmcDeviceOnlineRecord);
        // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), result);
    }

}
